package com.anjubao.parking.municipal.file.service;

import java.io.File;
import java.io.FileOutputStream;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import sun.misc.BASE64Decoder;

/**
 * @author anjubao
 */
@Service
public class FileServiceImpl   {

	@Value("${upload.filePath.win}")
	private String uploadPathWin;

	@Value("${upload.filePath.linux}")
	private String uploadPathLinux;

	@Value("${server.port}")
	private String serverPort;

	public String uploadFile(MultipartFile imageFile) throws Exception {
		String os = System.getProperty("os.name");
		String uploadPath=null;
		if(os.toLowerCase().startsWith("win")){
			uploadPath=uploadPathWin;
		}else{
			uploadPath=uploadPathLinux;
		}
		String fileName = System.nanoTime() + ".jpg";
		Date date = new Date();
		String filePath = uploadPath + new SimpleDateFormat("yyyy/MM/dd/").format(date);
		File targetFile = new File(filePath);
		String url = null;
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream outputStream = null;
		outputStream = new FileOutputStream(filePath + "/" + fileName);
		outputStream.write(imageFile.getBytes());
		outputStream.flush();
		outputStream.close();
		url = "/" + new SimpleDateFormat("yyyy/MM/dd/").format(date) + fileName;
		return url;
	}

	public String uploadBase64(String base64) throws Exception {
		String os = System.getProperty("os.name");
		String uploadPath=null;
		if(os.toLowerCase().startsWith("win")){
			uploadPath=uploadPathWin;
		}else{
			uploadPath=uploadPathLinux;
		}
		String fileName = System.nanoTime() + ".jpg";
		Date date = new Date();
		String filePath = uploadPath + new SimpleDateFormat("yyyy/MM/dd/").format(date);
		File targetFile = new File(filePath);
		String url = null;
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream outputStream = null;
		BASE64Decoder decoder = new BASE64Decoder();
		outputStream = new FileOutputStream(filePath + "/" + fileName);
		byte[] b = decoder.decodeBuffer(base64);
	/*	for (int i = 0; i < b.length; ++i) {
			if (b[i] < 0) {
				// 调整异常数据
				b[i] += 256;
			}
		}*/
		outputStream.write(b);
		outputStream.flush();
		outputStream.close();
		url = "/" + new SimpleDateFormat("yyyy/MM/dd/").format(date) + fileName;
		return url;
	}
}
